package com.njtoyo.taxi.admin.task;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.text.csv.CsvRow;
import cn.hutool.core.text.csv.CsvUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.ZipUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.http.HttpUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.njtoyo.taxi.admin.library.payment.cmb.CmbPayClient;
import com.njtoyo.taxi.admin.mapper.master.entity.DriverWithdraw;
import com.njtoyo.taxi.admin.mapper.master.enums.DriverWithdrawState;
import com.njtoyo.taxi.admin.service.business.DriverWithdrawService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 提现记录查询任务
 */
@Component
@Slf4j
public class DriverWithdrawQueryTask {

    @Autowired
    private DriverWithdrawService driverWithdrawService;


    /**
     * 每15分钟执行一次 查询转账结果
     */
    @Scheduled(cron = "0 0/15 * * * ? ")
    public void query() {
        log.info("开始执行提现记录查询任务");
        try {
            List<DriverWithdraw> driverWithdraws = driverWithdrawService.list(Wrappers.<DriverWithdraw>lambdaQuery()
                    .eq(DriverWithdraw::getState, DriverWithdrawState.operated)
                    .le(DriverWithdraw::getWithdrawTime, DateUtil.offsetMinute(DateUtil.date(), -15)));
            Map<String, List<DriverWithdraw>> driverWithdrawGroupMap = driverWithdraws.stream().collect(Collectors.groupingBy(DriverWithdraw::getBatchNo));
            String dateStr = DateUtil.format(DateUtil.date(), DatePattern.PURE_DATE_PATTERN);
            String activeProfile = SpringUtil.getActiveProfile();
            String filePatth = "";
            if ("test".equals(activeProfile)) {
                filePatth = "/Users/saber/Desktop/remit/upload/" + dateStr;
            } else {
                filePatth = "/bank/remit/upload/" + dateStr;
            }
            if (!FileUtil.exist(filePatth)) {
                FileUtil.mkParentDirs(filePatth);
            }
            for (Map.Entry<String, List<DriverWithdraw>> entry : driverWithdrawGroupMap.entrySet()) {
                String batchNo = entry.getKey();
                List<DriverWithdraw> driverWithdrawList = entry.getValue();
                Map<String, DriverWithdraw> driverWithdrawMap = driverWithdrawList.stream().collect(Collectors.toMap(DriverWithdraw::getSerialNo, Function.identity()));
                Map<String, Object> result = CmbPayClient.fileBatchQry(batchNo);
                if (result.get("code").equals("10000")) {
                    Object fileUrlObj = MapUtil.get(result, "data", Map.class).get("fileUrl");
                    if (ObjectUtil.isNotNull(fileUrlObj)) {
                        String fileUrl = fileUrlObj.toString();
                        String fileLocalUrl = filePatth + "/" + batchNo + ".zip";
                        File file = HttpUtil.downloadFileFromUrl(fileUrl, new File(fileLocalUrl));
                        log.info("代发批次{}存储地址：{},下载结果：{}", batchNo, file.getPath(), file.exists());
                        if (file.exists()) {
                            File unzipFile = ZipUtil.unzip(fileLocalUrl);
                            File targetFile = null;
                            if (unzipFile.isDirectory()) {
                                final File[] files = unzipFile.listFiles();
                                if (files != null) {
                                    targetFile = files[0];
                                }
                            }
                            List<CsvRow> rows = CsvUtil.getReader().read(new File(targetFile.getPath())).getRows();
                            for (CsvRow row : rows) {
                                if (row.getOriginalLineNumber() == 1) {
                                    continue;
                                }
                                String serialNo = StrUtil.removeAll(row.get(1), "`");
                                DriverWithdraw driverWithdraw = driverWithdrawMap.get(serialNo);
                                if (ObjectUtil.isNull(driverWithdraw)) {
                                    log.info("批次{}csv转账反馈中无流水号{}的结果", batchNo, row.get(1));
                                    continue;
                                }
                                String state = StrUtil.removeAll(row.get(5), "`");
                                if ("S".equals(state)) {
                                    driverWithdraw.setState(DriverWithdrawState.done);
                                    if (StrUtil.isNotBlank(row.get(8)) && StrUtil.isNotBlank(row.get(9))) {
                                        String receiptTime = StrUtil.removeAll(row.get(8), "`") + StrUtil.removeAll(row.get(9), "`");
                                        driverWithdraw.setReceiptTime(DateUtil.parse(receiptTime, "yyyyMMddHHmmss").toString());
                                    }
                                } else {
                                    driverWithdraw.setState(DriverWithdrawState.failed);
                                    driverWithdraw.setMsg(StrUtil.removeAll(row.get(6), "`"));
                                }
                                driverWithdrawService.updateById(driverWithdraw);
                            }
                        }

                    }
                }
            }

            log.info("执行提现记录查询任务完成");
        } catch (Exception e) {
            log.error("执行提现记录查询任务异常", e);
        }
    }
}
